package main

import (
	"fmt"
	"runtime"
	"time"
)

func newTask() {
	i := 0
	for true {
		i++
		fmt.Printf("new goroutine : i = %d\n", i)
		time.Sleep(1 * time.Second)
	}
}

// 匿名函数内部直接退出外部协程
func main3() {
	go func() {
		defer fmt.Println("A.defer")
		func() {
			defer fmt.Println("B.defer")
			runtime.Goexit() // 直接退出外层的goroutine，不包含main方法，输出B.defer A.defer
			fmt.Println("B")
		}()
		fmt.Println("A")
	}()

	for true {
		time.Sleep(1 * time.Second)
	}
}

// 匿名函数:
/**
  B
  B.defer
  A
  A.defer
*/
func main() {
	go func() {
		defer fmt.Println("A.defer")
		func(a int, b int) {
			defer fmt.Println("B.defer")
			fmt.Println("B=", a+b)
		}(10, 20)
		fmt.Println("A")
	}()

	for true {
		time.Sleep(1 * time.Second)
	}
}

// 通过关键字go：创建goroutine
func main1() {
	go newTask() // 通过go关键字创建一个goroutine协程

	//i := 0
	//for true {
	//    i ++
	//    fmt.Printf("main goroutine : i = %d\n", i)
	//    time.Sleep(1 * time.Second)
	//}
}
